import time

from selenium.common import NoSuchElementException, TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def click_element(driver, by_type, timeout, locator, message, keys):
    # 定义By类型
    if by_type == 'XPATH':
        by = By.XPATH
    elif by_type == 'CSS_SELECTOR':
        by = By.CSS_SELECTOR
    elif by_type == 'CLASS_NAME':
        by = By.CLASS_NAME
    elif by_type == 'ID':
        by = By.ID
    elif by_type == 'NAME':
        by = By.NAME
    else:
        raise ValueError("Invalid by_type provided")

    # 尝试点击元素，最多尝试10次，每次间隔timeout秒
    for _ in range(10):
        try:
            element = WebDriverWait(driver, timeout).until(
                EC.presence_of_element_located((by, locator)))
            if keys != None:
                element.send_keys(keys)
                input_value = element.get_attribute('value')
                if input_value == keys:
                    print(message + "输入成功")
                else:
                    print("输入失败，预期值：", keys, "实际值：", input_value)
                    raise Exception("输入失败，预期值：", keys, "实际值：", input_value)
            else:
                driver.execute_script("arguments[0].click();", element)
            print(message + "点击成功")
            break  # 如果成功点击，跳出循环
        except Exception:
            print(message + "点击失败,第" + str(_ + 1) + "次尝试")
            time.sleep(timeout)
    else:
        print(message + "点击失败,尝试10次后仍然失败")
        raise Exception("无法执行操作，尝试次数已达到上限")
